package com.iecas.utils;

import cn.hutool.core.lang.Console;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.iecas.enums.BizEnum;
import com.iecas.request.BaseRequest;
import com.iecas.request.Root;
import com.iecas.response.BaseResponse;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class RequestUtils {

    public static Root decode(ByteBuffer byteBuffer) {
        byte[] array = byteBuffer.array();
        return decode(array);
    }

    public static Root decode(byte[] bytes) {
        String jsonStr = new String(bytes);
        StaticLog.info("解码结果: {}", jsonStr);
        Root baseRequest = JSONUtil.toBean(jsonStr, Root.class);
        int code = baseRequest.getCode();
        BizEnum bizEnum = BizEnum.getByCode(code);
        return JSONUtil.toBean(jsonStr, bizEnum.getClazz());
    }

    public static ByteBuffer encode(Object request) {
        String jsonStr = JSONUtil.toJsonStr(request);
        int length = jsonStr.getBytes().length;
        ByteBuffer needSend = ByteBuffer.allocate(length + 4);
        needSend.putInt(length);
        needSend.put(jsonStr.getBytes());
//        Console.log("编码消息: {}", jsonStr);
        return needSend;
    }


    public static byte[] getExpectBytes(SocketChannel socketChannel, int expect) throws IOException {
        StaticLog.info("希望:{}",expect);
        ByteBuffer temp = ByteBuffer.allocate(4096);
        byte[] result = new byte[expect];
        int totalRead = 0;
        while (totalRead < expect) {
            int needRead = Math.min(temp.capacity(), expect - totalRead);
            temp.clear();
            temp.limit(needRead);

            needRead = socketChannel.read(temp);
            StaticLog.info("read:{}",needRead);
            temp.flip();
            temp.get(result, totalRead, needRead);

            totalRead += needRead;
            StaticLog.info("希望:{},真实:{}", expect, totalRead);
        }
        return result;
    }

}
